/*网关模块*/
package tugou

import (
	"time"
	"tugou/logs"
	"tugou/utils"
	"tugou/web"
	"tugou/websocket"
)

type gate interface {
	getSessionInfo() SessionInfo
}
type Gate struct {
	info          ModuleInfo                //基本信息
	msg           chan messageToGate        //消息
	addDynamic    chan sessionDynamicModule //添加动态模块
	removeDynamic chan sessionInfo          //移除动态模块
	addFix        chan sessionFix           //添加固定模块
	removeFix     chan sessionInfo          //移除固定模块
	shut          chan string               //主动关闭关闭网关模块
	disconnect    chan bool                 //断网
	ws            *websocket.Conn
	ticker        *time.Ticker               //定时器
	dynamics      map[string]*sessionDynamic //动态模块的本地
	fixs          map[string]*sessionFix     //固定模块
	handler       handler
	extend        gate //扩展
}

func (this *Gate) init(c *web.Context, extend interface{}) { //初始化

}
func (this *Gate) run() {

}
func (this *Gate) readChan() {

}
func (this *Gate) readWs() {
	//网络读取
	defer func() {
		if err := recover(); err != nil {
			this.disconnect <- true
			logs.Critical("玩家网络读取协程发生恐慌", err)
		}
	}()
	for {
		msg := messageClient{}
		_, msgByte, err := this.ws.ReadMessage()
		if err != nil {
			logs.Error("websocket关闭类型错误", err)
			this.disconnect <- true
			break
		}
		err = utils.ToStruct(msgByte, &msg)
		if err != nil {
			logs.Error("玩家模块读取json错误:", err, "id:", this.id)
			msg.M = "World"
			msg.F = "Err"

		} else {
			logs.Debug("读取到网络数据")
			if msg.M == "" {
				err := this.handler.callAsync(Func_Perfix_By_Client, msg.F, msg.D)
				if err != nil {
					logs.Error(err)
				}
			} else {
				dynamic, ok := this.dynamics[msg.M]
				if d, ok := this.dynamics[msg.M]; ok {
					err := dynamic.sendByClient(msg.D, msg.F)

					if err != nil {
						logs.Error(err)
					}
				} else if fix, ok := this.fixs[msg.M]; ok {
					err := fix.sendByClient(msg.D, msg.F)
					if err != nil {
						logs.Error(err)
					}
				} else {
					logs.Error("没有找到模块")
				}
			}
		}
	}
}
func (this *Gate) getSessionInfo() SessionInfo {
	info := &sessionInfo{}
	info.Id = this.id
	info.Name = this.name
	info.Type = Session_Type_Gate
	info.Version = this.version
	return info
}

func (this *Gate) getSession() SessionGate {
	sessionGate := &sessionGateModule{}
	sessionGate.SessionInfo = this.getSessionInfo()
	sessionGate.set(this.msg, this.addDynamic, this.removeDynamic, this.shut)
	return sessionGate
}
